package com.hyacinth.forumbite.controller;

import com.hyacinth.forumbite.common.AppConfig;
import com.hyacinth.forumbite.common.AppResult;
import com.hyacinth.forumbite.model.User;
import com.hyacinth.forumbite.service.FileUploadService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileUploadController {
    @Resource
    private FileUploadService fileUploadService;

    @Operation(summary = "用户上传头像")
    @PostMapping("/upload")
    public AppResult<String> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        if (file == null) {
            return AppResult.failed("文件为空");
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getDeleteState() == 1 || user.getState() == 1) {
            return AppResult.failed("用户状态异常,修改失败");
        }
        String avatarUrl = fileUploadService.upload(file, user.getId());
        // 更新session信息
        user.setAvatarUrl(avatarUrl);
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success(avatarUrl);
    }
}
